/*
 * FileName: CountTask.java
 * Author:   zzw
 * Date:     2018年05月14日
 * Description:
 */
package com.zzw.thread;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class CountTask extends RecursiveTask<Long> {
    private static final int THRESHOLD = 10000;
    private long start;
    private long end;

    public CountTask(long start,long end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end - start) < THRESHOLD;
        if(canCompute){
            for (long i = start;i <= end; i++){
                sum += i;
            }
        }
        else {
            long step = (start + end) / 100;
            ArrayList<CountTask> countTasks = new ArrayList<>();
            long pos = start;
            int i;
            for(i = 0;i < 100;i++){
                long lastOne = pos + step;
                if(lastOne > end){
                    lastOne = end;
                }
                CountTask subTask = new CountTask(pos + 1,lastOne);
                pos += step;
                countTasks.add(subTask);
                subTask.fork();
            }
            for (CountTask t:countTasks){
                sum += t.join();
            }
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask task = new CountTask(0,10001);
        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        Long res = result.get();
        System.out.println("res:" + res);
        long sum = 0;
        for (int i = 0;i <= 10001;i++){
            sum += i;
        }
        System.out.println(sum);
    }
}
